<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 消息提示 -->
      <el-alert title="添加商品信息" :closable="false" type="info" center show-icon></el-alert>
      <!-- 步骤图 -->
      <el-steps align-center :active="activeIndex - 0" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 添加商品的表单 -->
      <el-form ref="addGoodsForm" :rules="addGoodsFormRules" :model="addGoodsFormData">
        <!-- tab标签页 -->
        <el-tabs @tab-click="tabClick" v-model="activeIndex" tab-position="left" :before-leave="beforeLeave">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsFormData.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addGoodsFormData.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="addGoodsFormData.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model="addGoodsFormData.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader
                v-model="addGoodsFormData.goods_cat"
                :options="goodsCate"
                :props="cascaderPros"
                @change="handleChange">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="item in manyData" :key="item.attr_id" :label="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals" size="mini">
                <el-checkbox v-for="(item, index) in item.attr_vals" :key="index" :label="item" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="item in onlyData" :key="item.attr_name" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :headers="uploadHeaders"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="uploadSuccess"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addGoodsFormData.goods_introduce"></quill-editor>
            <el-button @click="submitGoods" type="primary" style="margin-top: 20px;">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog :visible.sync="preViewImgDialogVisible" width="50%">
      <img :src="imgUrl" style="width:100%;" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { cloneDeep } from 'lodash'
export default {
  data () {
    return {
      activeIndex: 0,
      // 添加商品的表单数据
      addGoodsFormData: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 级联选择器绑定的id
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      // 添加商品表单验证规则
      addGoodsFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 5 个字符', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ]
      },
      // 商品列表数据，级联选择器数据
      goodsCate: [],
      // 级联选择器配置对象
      cascaderPros: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id'
      },
      manyData: [],
      onlyData: [],
      // 图片上传请求头
      uploadHeaders: {
        Authorization: sessionStorage.getItem('token')
      },
      // 预览图片的对话框
      preViewImgDialogVisible: false,
      // 图片url路径
      imgUrl: ''
    }
  },
  methods: {
    // 获取商品分类的数据
    async getGoodsCate () {
      const { data: res } = await this.$axios.get('/categories')
      if (res.meta.status !== 200) return this.$message.error('获取列表数据失败！')
      this.goodsCate = res.data
      // console.log(res)
    },
    // 级联选择器change事件
    handleChange () {
      if (this.addGoodsFormData.goods_cat.length !== 3) {
        this.addGoodsFormData.goods_cat = []
        this.$message('请选择三级分类！')
      }
    },
    // tab离开之前事件
    beforeLeave (activeName, oldName) {
      if (oldName === '0' && this.addGoodsFormData.goods_cat.length !== 3) {
        this.$message('请选择三级分类！')
        return false
      }
    },
    // tab点击事件
    tabClick () {
      if (this.activeIndex === '1') {
        this.getGoodsParams('many')
      } else if (this.activeIndex === '2') {
        this.getGoodsParams('only')
      }
    },
    // 获取商品分类参数
    async getGoodsParams (sel) {
      const { data: res } = await this.$axios.get('categories/' + this.cateId + '/attributes', { params: { sel: sel } })
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取分类参数失败！')
      if (sel === 'many') {
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(',')
        })
        this.manyData = res.data
      } else {
        this.onlyData = res.data
      }
    },
    // 预览图片
    handlePreview (file) {
      // console.log(23)
      this.preViewImgDialogVisible = true
      this.imgUrl = 'http://127.0.0.1:8888/' + file.response.data.tmp_path
    },
    // 移除图片
    handleRemove (file) {
      const index = this.addGoodsFormData.pics.findIndex(item => {
        return item.pic === file.response.data.tmp_path
      })
      this.addGoodsFormData.pics.splice(index, 1)
      // console.log('移除图片！')
    },
    // 图片上传成功回调函数
    uploadSuccess (res) {
      this.addGoodsFormData.pics.push({ pic: res.data.tmp_path })
    },
    // 添加商品
    submitGoods () {
      // const form = JSON.parse(JSON.stringify(this.addGoodsFormData))
      this.$refs.addGoodsForm.validate(async valid => {
        if (!valid) return this.$message.error('请填写必填项！')
        const form = cloneDeep(this.addGoodsFormData)
        form.goods_cat = form.goods_cat.join(',')
        this.manyData.forEach(item => {
          form.attrs.push({ attr_id: item.attr_id, attr_value: item.attr_vals.join(' ') })
        })
        this.onlyData.forEach(item => {
          form.attrs.push({ attr_id: item.attr_id, attr_value: item.attr_vals })
        })
        console.log(form)
        const { data: res } = await this.$axios.post('goods', form)
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加商品失败！')
        this.$message.success('添加商品成功！')
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    cateId () {
      if (this.addGoodsFormData.goods_cat.length !== 3) {
        return null
      }
      return this.addGoodsFormData.goods_cat[2]
    }
  },
  created () {
    this.getGoodsCate()
  }
}
</script>

<style lang='less' scoped>
.el-steps{
  margin-top: 20px;
}
/deep/ .el-step__title{
  font-size: 12px;
}
.el-checkbox{
  margin-right: 0;
}
/deep/ .ql-editor{
  height: 300px;
}
</style>
